/*****************************************************************************
 * Copyright (C) Stacy Curl. All rights reserved.                            *
 * ------------------------------------------------------------------------- *
 * The software in this package is published under the terms of the BSD      *
 * style license a copy of which has been included with this distribution in *
 * the LICENSE.txt file.                                                     *
 *****************************************************************************/
package picounit.features.verify.constraint;

import java.lang.reflect.Array;

public class ArrayModifierImpl implements ArrayModifier {
	private final Modifier modifier;
	private final Class modifiedClass;

	public ArrayModifierImpl(Modifier modifier, Class modifiedClass) {
		this.modifier = modifier;
		this.modifiedClass = modifiedClass;
	}

	public final Object modify(Object array) {
		if (array == null) {
			return "null";
		}

		if (!array.getClass().isArray()) {
			return modifyElement(array);
		}

		int arrayLength = Array.getLength(array);

		Object modifiedArray = Array.newInstance(modifiedClass, arrayLength);

		for (int index = 0; index < arrayLength; index++ ) {
			Array.set(modifiedArray, index, modifier.modify(Array.get(array, index)));
		}

		return modifiedArray;
	}

	public final String getName() {
		return modifier.getName();
	}

	public final Object modifyElement(Object element) {
		return modifier.modify(element);
	}
}
